package com.sen.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author Kisen
 * @email lqs0911@qq.com
 * @date 2022/11/5 15:59
 * @detail 单点登录
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String userInfo = redisTemplate.opsForValue().get(token);
        return userInfo;
    }

    @GetMapping("login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String ssoToken) {
        if (!StringUtils.isEmpty(ssoToken)) {
            //说明之前有人登录过，浏览器留下了痕迹
            return "redirect:" + url + "?token=" + ssoToken;
        }
        model.addAttribute("url", url);

        return "login";
    }

    @PostMapping("doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String url,
                          HttpServletResponse response) {

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录成功，跳回之前页面
            //把登录成功的用户存起来。
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            Cookie ssoToken = new Cookie("sso_token", uuid);
            response.addCookie(ssoToken);
            return "redirect:" + url + "?token=" + uuid;
        }

        //登录失败，展示登录页
        return "login";
    }


}
